import React, { useState } from 'react';
import { createPortal } from 'react-dom';
import { lightCCApi } from '../services/lightcc-api';
import { historyManager } from '../services/historyManager';
import { notification } from './Notification';
import UploadResult from './UploadResult';
import './StopTaskFloatingInput.css';

const StopTaskFloatingInput: React.FC = () => {
  const [isExpanded, setIsExpanded] = useState(false);
  
  // 原有状态
  const [taskId, setTaskId] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [resultTaskId, setResultTaskId] = useState('');
  const [isGettingResult, setIsGettingResult] = useState(false);
  const [runningTasks, setRunningTasks] = useState<any[]>([]);
  const [isLoadingRunningTasks, setIsLoadingRunningTasks] = useState(false);
  
  // API查询相关状态
  const [queryTaskId, setQueryTaskId] = useState('');
  const [apiQueryResult, setApiQueryResult] = useState<any>(null);
  const [isQueryingApi, setIsQueryingApi] = useState(false);
  const [taskApiMapping, setTaskApiMapping] = useState<any[]>([]);
  
  // 任务列表弹窗状态
  const [showTaskModal, setShowTaskModal] = useState(false);
  
  // UploadResult 弹窗状态
  const [showUploadResult, setShowUploadResult] = useState(false);
  const [resultImageUrl, setResultImageUrl] = useState<string | null>(null);

  // 切换展开/收起
  const toggleExpanded = () => {
    setIsExpanded(!isExpanded);
  };

  // 处理停止任务
  const handleStopTask = async () => {
    if (!taskId.trim()) {
      notification.warning('请输入任务ID');
      return;
    }

    setIsLoading(true);
    try {
      await lightCCApi.interruptTask(taskId.trim());
      notification.success('任务已停止');
      setTaskId('');
    } catch (error) {
      console.error('停止任务失败:', error);
      notification.error('停止任务失败: ' + (error as Error).message);
    } finally {
      setIsLoading(false);
    }
  };

  // 处理获取任务结果
  const handleGetResult = async () => {
    if (!resultTaskId.trim()) {
      notification.warning('请输入任务ID');
      return;
    }

    setIsGettingResult(true);
    try {
      const result = await lightCCApi.getTaskResult(resultTaskId.trim());
      console.log('任务结果:', result);
      
      if (result && result.result && result.result.length > 0) {
        // 使用第一张图片作为结果
        setResultImageUrl(result.result[0]);
        setShowUploadResult(true);
        notification.success('任务结果已获取，正在显示图片');
      } else {
        notification.warning('任务结果中没有图片');
      }
    } catch (error) {
      console.error('获取任务结果失败:', error);
      notification.error('获取任务结果失败: ' + (error as Error).message);
    } finally {
      setIsGettingResult(false);
    }
  };

  // 处理获取所有任务（包括运行中和已完成）
  const handleGetRunningTasks = async () => {
    setIsLoadingRunningTasks(true);
    try {
      // 直接调用API获取所有任务，不进行过滤
      const response = await fetch('/api/lightcc/task/result', {
        method: 'GET',
        headers: {
          'X-Api-Key': '6948fec62ff649848bc0be21a49275f6',
          'Content-Type': 'application/json'
        }
      });
      
      const result = await response.json();
      console.log('所有任务响应:', result);
      
      if (result.code === 200 && result.data) {
        setRunningTasks(result.data);
        const runningCount = result.data.filter((task: any) => task.status === 1).length;
        const completedCount = result.data.filter((task: any) => task.status === 4).length;
        const failedCount = result.data.filter((task: any) => task.status === 3).length;
        
        notification.info(`总共 ${result.data.length} 个任务：运行中 ${runningCount} 个，已完成 ${completedCount} 个，失败 ${failedCount} 个`);
        
        // 自动打开任务列表弹窗
        console.log('准备打开任务列表弹窗，任务数量:', result.data.length);
        setShowTaskModal(true);
      } else {
        notification.error('获取任务失败: ' + result.msg);
      }
    } catch (error) {
      console.error('获取任务失败:', error);
      notification.error('获取任务失败: ' + (error as Error).message);
    } finally {
      setIsLoadingRunningTasks(false);
    }
  };

  // 处理查询API文件路径
  const handleQueryApi = () => {
    if (!queryTaskId.trim()) {
      notification.warning('请输入任务ID');
      return;
    }

    setIsQueryingApi(true);
    try {
      const historyItem = historyManager.findByTaskId(queryTaskId.trim());
      if (historyItem) {
        setApiQueryResult({
          taskId: historyItem.taskId,
          apiFilePath: historyItem.apiFilePath,
          workflowName: historyItem.workflowName,
          date: historyItem.date,
          status: historyItem.status,
          business: historyItem.context.selectedBusiness,
          feature: historyItem.context.selectedFeature
        });
        console.log('API查询结果:', {
          taskId: historyItem.taskId,
          apiFilePath: historyItem.apiFilePath,
          workflowName: historyItem.workflowName,
          date: historyItem.date,
          status: historyItem.status,
          business: historyItem.context.selectedBusiness,
          feature: historyItem.context.selectedFeature
        });
        notification.success('API查询成功，请查看控制台');
      } else {
        setApiQueryResult(null);
        notification.warning('未找到该任务ID对应的记录');
      }
    } catch (error) {
      console.error('查询API失败:', error);
      notification.error('查询API失败: ' + (error as Error).message);
    } finally {
      setIsQueryingApi(false);
    }
  };

  // 获取所有任务API映射
  const handleGetTaskApiMapping = () => {
    try {
      const mapping = historyManager.getTaskApiMapping();
      setTaskApiMapping(mapping);
      console.log('任务API映射:', mapping);
      if (mapping.length === 0) {
        notification.info('当前没有任务API映射记录');
      } else {
        notification.info(`找到 ${mapping.length} 条任务API映射记录，请查看控制台`);
      }
    } catch (error) {
      console.error('获取任务API映射失败:', error);
      notification.error('获取任务API映射失败: ' + (error as Error).message);
    }
  };

  // 任务列表弹窗组件
  const TaskModal = () => {
    if (!showTaskModal) return null;

    return createPortal(
      <div className="task-modal-overlay" onClick={() => setShowTaskModal(false)}>
        <div className="task-modal" onClick={(e) => e.stopPropagation()}>
          <div className="task-modal-header">
            <h3>所有任务 ({runningTasks.length}个)</h3>
            <button 
              className="task-modal-close"
              onClick={() => setShowTaskModal(false)}
            >
              ✕
            </button>
          </div>
          <div className="task-modal-content">
            {runningTasks.map((task) => {
              const getStatusText = (status: number) => {
                switch (status) {
                  case 0: return '排队中';
                  case 1: return '运行中';
                  case 2: return '已中断';
                  case 3: return '异常/失败';
                  case 4: return '已完成';
                  default: return `状态${status}`;
                }
              };
              
              const getStatusColor = (status: number) => {
                switch (status) {
                  case 0: return '#ffa500'; // 橙色
                  case 1: return '#00ff00'; // 绿色
                  case 2: return '#ff0000'; // 红色
                  case 3: return '#ff0000'; // 红色
                  case 4: return '#0080ff'; // 蓝色
                  default: return '#666666'; // 灰色
                }
              };
              
              return (
                <div key={task.taskId} className="task-modal-item" style={{borderLeft: `4px solid ${getStatusColor(task.status)}`}}>
                  <div className="task-item-header">
                    <span className="task-id">任务ID: {task.taskId}</span>
                    <span className="task-status" style={{color: getStatusColor(task.status)}}>
                      {getStatusText(task.status)}
                    </span>
                  </div>
                  <div className="task-item-details">
                    {task.process !== undefined && <div><strong>进度:</strong> {task.process}%</div>}
                    {task.msg && <div><strong>消息:</strong> {task.msg}</div>}
                    {task.costPoint !== undefined && <div><strong>消耗点数:</strong> {task.costPoint}</div>}
                    {task.startTime && <div><strong>开始时间:</strong> {new Date(task.startTime).toLocaleString()}</div>}
                    {task.endTime && <div><strong>结束时间:</strong> {new Date(task.endTime).toLocaleString()}</div>}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>,
      document.body
    );
  };

  return (
    <div 
      className={`stop-task-floating-input ${isExpanded ? 'expanded' : 'collapsed'}`}
    >
      {/* 悬浮按钮 */}
      <div className="floating-button" onClick={toggleExpanded}>
        <div className="button-icon">
          {isExpanded ? '✕' : '⚙️'}
        </div>
        {/* <div className="button-text">Dev</div> */}
      </div>

      {/* 展开的内容 */}
      {isExpanded && (
        <div className="expanded-content">
          <div className="stop-task-info">
            <div className="stop-task-title">开发工具</div>
            <div className="stop-task-status">任务管理</div>
          </div>
        
        {/* 停止任务 */}
        <div className="stop-task-input-group">
          <div className="stop-task-section-title">停止任务</div>
          <input
            type="text"
            value={taskId}
            onChange={(e) => setTaskId(e.target.value)}
            placeholder="输入任务ID"
            className="stop-task-input"
          />
          <button 
            className="stop-task-button"
            onClick={handleStopTask}
            disabled={isLoading || !taskId.trim()}
          >
            {isLoading ? '停止中...' : '停止任务'}
          </button>
        </div>

        {/* 查询所有任务 */}
        <div className="stop-task-input-group">
          <div className="stop-task-section-title">所有任务</div>
          <button 
            className="stop-task-button running-tasks-button"
            onClick={handleGetRunningTasks}
            disabled={isLoadingRunningTasks}
          >
            {isLoadingRunningTasks ? '查询中...' : '查询所有任务'}
          </button>
        </div>

        {/* 获取任务结果 */}
        <div className="stop-task-input-group">
          <div className="stop-task-section-title">获取结果</div>
          <input
            type="text"
            value={resultTaskId}
            onChange={(e) => setResultTaskId(e.target.value)}
            placeholder="输入任务ID"
            className="stop-task-input"
          />
          <button 
            className="stop-task-button get-result-button"
            onClick={handleGetResult}
            disabled={isGettingResult || !resultTaskId.trim()}
          >
            {isGettingResult ? '获取中...' : '获取结果'}
          </button>
        </div>

        {/* 查询API文件路径 */}
        <div className="stop-task-input-group">
          <div className="stop-task-section-title">查询API文件</div>
          <input
            type="text"
            value={queryTaskId}
            onChange={(e) => setQueryTaskId(e.target.value)}
            placeholder="输入任务ID"
            className="stop-task-input"
          />
          <button 
            className="stop-task-button query-api-button"
            onClick={handleQueryApi}
            disabled={isQueryingApi || !queryTaskId.trim()}
          >
            {isQueryingApi ? '查询中...' : '查询API'}
          </button>
        </div>

        {/* 获取所有任务API映射 */}
        <div className="stop-task-input-group">
          <div className="stop-task-section-title">任务API映射</div>
          <button 
            className="stop-task-button mapping-button"
            onClick={handleGetTaskApiMapping}
          >
            获取所有映射
          </button>
        </div>

        {/* 任务列表弹窗按钮 */}
        {/* {runningTasks.length > 0 && (
          <div className="stop-task-input-group">
            <div className="stop-task-section-title">任务列表</div>
            <button 
              className="stop-task-button task-list-button"
              onClick={() => setShowTaskModal(true)}
            >
              查看所有任务 ({runningTasks.length}个)
            </button>
          </div>
        )} */}

        {/* 显示API查询结果 */}
        {apiQueryResult && (
          <div className="stop-task-result">
            <div className="stop-task-section-title">API查询结果</div>
            <div className="result-info">
              <div>任务ID: {apiQueryResult.taskId}</div>
              <div>API文件路径: {apiQueryResult.apiFilePath}</div>
              <div>工作流名称: {apiQueryResult.workflowName}</div>
              <div>创建时间: {apiQueryResult.date}</div>
              <div>状态: {apiQueryResult.status}</div>
              <div>业态: {apiQueryResult.business}</div>
              <div>功能: {apiQueryResult.feature}</div>
            </div>
          </div>
        )}

        {/* 显示任务API映射 */}
        {taskApiMapping.length > 0 && (
          <div className="stop-task-result">
            <div className="stop-task-section-title">任务API映射 ({taskApiMapping.length}条)</div>
            <div className="result-info">
              {taskApiMapping.slice(0, 5).map((mapping, index) => (
                <div key={index} className="mapping-item">
                  <div>任务ID: {mapping.taskId}</div>
                  <div>API路径: {mapping.apiFilePath}</div>
                  <div>工作流: {mapping.workflowName}</div>
                  <div>时间: {mapping.date}</div>
                  <hr />
                </div>
              ))}
              {taskApiMapping.length > 5 && (
                <div>... 还有 {taskApiMapping.length - 5} 条记录</div>
              )}
            </div>
          </div>
        )}

        </div>
      )}

      {/* 使用Portal渲染任务列表弹窗 */}
      <TaskModal />
      
      {/* 使用Portal渲染UploadResult弹窗 */}
      {showUploadResult && resultImageUrl && (
        <UploadResult
          imagePreview={resultImageUrl}
          onEdit={() => {
            setShowUploadResult(false);
            notification.info('编辑功能待实现');
          }}
          onRegenerate={() => {
            setShowUploadResult(false);
            notification.info('重新生成功能待实现');
          }}
          onDownload={() => {
            // 下载图片
            const link = document.createElement('a');
            link.href = resultImageUrl;
            link.download = `task-result-${resultTaskId}.png`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            notification.success('图片已开始下载');
          }}
          onShare={() => {
            // 复制链接到剪贴板
            navigator.clipboard.writeText(resultImageUrl);
            notification.success('图片链接已复制到剪贴板');
          }}
          onClose={() => {
            setShowUploadResult(false);
            setResultImageUrl(null);
          }}
          isVisible={showUploadResult}
          prompt={`任务ID: ${resultTaskId}`}
          format="任务结果"
          aspectRatio="自动"
          resolution="原始"
        />
      )}
    </div>
  );
};

export default StopTaskFloatingInput;
